package com.example.ad.sdk.domain.repositories.base

import com.example.ad.sdk.domain.helper.BuildConfigHelper
import com.example.ad.sdk.domain.repositories.interceptor.CommonParamsInterceptor
import com.example.ad.sdk.domain.repositories.interceptor.HeaderInterceptor
import com.example.ad.sdk.domain.repositories.interceptor.JsonConverterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

/**
 * 抽象类 BaseRetrofitClient，用于构建 Retrofit 客户端
 */
abstract class BaseRetrofitClient {

    companion object {
        // 请求超时时间常量
        private const val TIME_OUT = 35
    }

    /**
     * OkHttpClient 实例属性，用于发起网络请求
     */
    private val client: OkHttpClient
        get() {
            // 创建 OkHttpClient.Builder 实例
            val builder = OkHttpClient.Builder()
            // 创建 HttpLoggingInterceptor 实例
            val logging = HttpLoggingInterceptor()
            // 根据是否是调试模式设置日志级别
            if (BuildConfigHelper.isOpenLog) {
                logging.level = HttpLoggingInterceptor.Level.BODY
            } else {
                logging.level = HttpLoggingInterceptor.Level.BASIC
            }
            // 添加日志拦截器
            builder.addInterceptor(logging)
                // 设置连接超时时间
                .connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
                // 添加 Header 拦截器
                .addInterceptor(HeaderInterceptor())
                .addInterceptor(CommonParamsInterceptor())
            // 允许子类处理 Builder
            handleBuilder(builder)
            // 构建并返回 OkHttpClient 实例
            return builder.build()
        }

    protected abstract fun getBaseHost(): String

    /**
     * 抽象方法，允许子类自定义 OkHttpClient.Builder 的行为
     * @param builder OkHttpClient.Builder 实例，子类可以对其进行配置
     */
    protected abstract fun handleBuilder(builder: OkHttpClient.Builder)


    /**
     * 创建指定服务接口的实例
     * @param serviceClass 服务接口的类类型
     * @return 返回指定服务接口的实例
     */
    fun <S> getService(serviceClass: Class<S>): S {
        // 使用 Retrofit.Builder 创建 Retrofit 实例并生成服务接口实例
        val baseUrl = getBaseHost()
        return Retrofit.Builder()
            .client(client)
            .baseUrl(if (baseUrl.isNotEmpty()) baseUrl else "https://ukamobi.com/cloud")
            .addConverterFactory(JsonConverterFactory.create())
            .build().create(serviceClass)
    }
}